<?php

namespace app\admin\controller;

use app\common\model\UserRelation as RelationModel;
use think\Request;
use app\common\lib\Util;

class UserRelation extends Base
{
    //好友关系名列表
    public function index()
    {
        $relationList = RelationModel::paginate(15);
        $this->assign('title', '亲属关系');
        $this->assign('list', $relationList);
        return $this->fetch();
    }

    public function create()
    {
        return $this->fetch();
    }

    public function store(Request $request, RelationModel $model)
    {
        $relationName = $request->relation_name;
        if (empty($relationName) && $relationName != '0') {
            return Util::apiResponse([], '关系名称不能为空', -1);
        }
        $res = $model->save(['name' => $relationName]);
        if (!$res) {
            return Util::apiResponse([], '新增失败', -1);
        }
        return Util::apiResponse([], '', 1);
    }

    public function edit($id, RelationModel $model)
    {
        $relationInfo = $model->find($id);
//        if (!$relationInfo) {
//            $this->error('该记录不存在');
//        }
//        $this->assign('relation_info', $relationInfo);
//        $this->assign('id', $id);
//        return $this->fetch();
        return Util::apiResponse($relationInfo, '', 1);
    }

    public function update($id, Request $request, RelationModel $model)
    {
        $relationName = $request->relation_name;
        if (empty($relationName) && $relationName != '0') {
            return Util::apiResponse([], '菜单名不能为空', -1);
        }
        $data = ['name' => $relationName];
        $upd = $model->save($data, ['id' => $id]);
        if ($upd === false) {
            return Util::apiResponse([], '更新失败', -1);
        }
        return Util::apiResponse([], '', 1);

    }

    public function delete($id, RelationModel $model)
    {
        $exist = $model->find($id);
        if (!$exist) {
            return Util::apiResponse([], '该记录不存在', -1);
        }
        $res = $model->destroy($id);
        if (!$res) {
            return Util::apiResponse([], '删除失败', -1);
        }
        return Util::apiResponse([], '', 1);
    }
}
